package com.inforest.model;

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 用户实体类，包含基本用户信息及输入校验。
 */
public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String email;
    private String phone;

    // 邮箱和电话校验的预编译正则 Pattern（Java 11 风格优化）
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");
    private static final Pattern PHONE_PATTERN = Pattern.compile("^\\d{10,15}$");

    /**
     * 创建用户（不含ID，适用于新增用户）
     */
    public User(String name, String gender, int age, String email, String phone) {
        setName(name);
        setGender(gender);
        setAge(age);
        setEmail(email);
        setPhone(phone);
    }

    /**
     * 创建用户（含ID，适用于更新或读取）
     */
    public User(int id, String name, String gender, int age, String email, String phone) {
        this(name, gender, age, email, phone);
        setId(id);
    }

    public User() {

    }

    // 校验：非空字符串
    private void validateInput(String value, String field) {
        if (value == null || value.isBlank()) {
            throw new IllegalArgumentException(field + "不能为空");
        }
    }

    private void validateAge(int age) {
        if (age < 0 || age > 120) {
            throw new IllegalArgumentException("年龄必须在 0 到 120 之间");
        }
    }

    private void validateEmail(String email) {
        Objects.requireNonNull(email, "邮箱不能为空");
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
    }

    private void validatePhone(String phone) {
        Objects.requireNonNull(phone, "电话不能为空");
        if (!PHONE_PATTERN.matcher(phone).matches()) {
            throw new IllegalArgumentException("电话号码格式不正确");
        }
    }

    // --- Getter / Setter with Validation ---

    public int getId() {
        return id;
    }

    public void setId(int id) {
        if (id < 0) {
            throw new IllegalArgumentException("ID 不能为负数");
        }
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        validateInput(name, "姓名");
        this.name = name.trim();
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        validateInput(gender, "性别");
        this.gender = gender.trim();
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        validateAge(age);
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        validateEmail(email);
        this.email = email.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        validatePhone(phone);
        this.phone = phone.trim();
    }
}
